﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraTab;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using simpleHotel.Client.UserControls;
using simpleHotel.Client.Hotel;
using System.Threading;
using System.Linq;


namespace simpleHotel.Client
{
    public partial class MainForm : RibbonForm
    {
        public Dictionary<string, BarButtonItem> Features { get; set; }

        public MainForm()
        {
            InitializeComponent();
            InitSkinGallery();

            Features = new Dictionary<string,BarButtonItem>
            {
                {"bookingcancellation", this.biBookingCancellation},
                {"bookinglist", this.biBookingList},
                {"hotellist", this.biHotelList},
                {"updaterooms", this.biUpdateRoom },
                {"newslist", this.biNewsList },
                {"hotelinfor", this.biHotelInfor},
                {"userlist", this.biUserList},
                {"logout", this.biLogout},
                {"login", this.biLogin},
            };
            
        }

        private void InitSkinGallery()
        {
            SkinHelper.InitSkinGallery(rgbiSkins, true);
        }

        public void EnableFeaturesFirstTime()
        {
            foreach (var keypair in Features)
                keypair.Value.Enabled = false;
            Features["login"].Enabled = true;
        }

        public void EnableFeatures(bool isAdmin)
        {
            foreach (var keypair in Features)
                keypair.Value.Enabled = true;
            Features["login"].Enabled = false;

            if (isAdmin)
            {
                Features["hotelinfor"].Enabled = false;
                return;
            }

            Features["bookingcancellation"].Enabled = false;
            Features["bookinglist"].Enabled = false;
            Features["newslist"].Enabled = false;
            Features["hotellist"].Enabled = false;
            Features["userlist"].Enabled = false;
            
        }

        private void LoadWelcomeTab()
        {
            this.tabMain.TabPages.Clear();
            var firstForm = new ucFirst { Title = "Start" };
            OpenTab(firstForm);
        }

        public void OpenTab(BaseUserControl form)
        {
            var fType = form.GetType();
            for (int i = 0; i < this.tabMain.TabPages.Count; i++)
            {
                var t = this.tabMain.TabPages[i];
                if (t.Controls.Count == 0)
                    continue;
                if ((t.Controls[0] as BaseCaptionControl).GetBaseUserControl().GetType() == fType)
                {
                    this.tabMain.SelectedTabPage = t;
                    return;
                }
            }

            var tab = MakeNewTab(form.Title);
            form.FormMain = this;
            form.Dock = DockStyle.Fill;
            var gc = MakeNewGroupControl(form.Title);
            AssociateCaptionAndUserControl(gc, form);
            gc.AddControls(form);
            tab.Controls.Add(gc);
            tabMain.SelectedTabPage = tab;
        }

        public void AssociateCaptionAndUserControl(BaseCaptionControl captionCtrl, BaseUserControl userCtrl)
        {
            captionCtrl.ButtonClick += userCtrl.CaptionButtonClick;
            userCtrl.ControlCaption = captionCtrl;
        }

        public void ClearAllTabs()
        {
            this.tabMain.TabPages.Clear();
        }

        public void CloseTab(string text)
        {
            for (int i = 0; i < this.tabMain.TabPages.Count; i++)
            {
                var tabPage = this.tabMain.TabPages[i];
                if (tabPage.Text.ToLower() == text.ToLower())
                {
                    var ctrl = tabPage.Controls.Count > 0 ? tabPage.Controls[0] : null;
                    if (ctrl != null)
                    {
                        if (ctrl is BaseCaptionControl)
                        {
                            string result = (ctrl as BaseCaptionControl).GetBaseUserControl().Validate();
                            if (result == string.Empty)
                            {
                                ctrl.Dispose();
                                this.tabMain.TabPages.Remove(tabPage);
                                break;
                            }
                            else
                            {
                                MessageBox.Show(result);
                                break;
                            }
                        }
                    }
                }
            }
        }

        public void TabCloseButtonClick()
        {
            var currentTab = this.tabMain.SelectedTabPage;
            if (currentTab == null)
                return;
            var ctrl = currentTab.Controls.Count > 0 ? currentTab.Controls[0] : null;
            if (ctrl != null)
            {
                if (ctrl is BaseCaptionControl)
                {
                    string result = (ctrl as BaseCaptionControl).GetBaseUserControl().Validate();
                    if (result == string.Empty)
                    {
                        ctrl.Dispose();
                        this.tabMain.TabPages.Remove(currentTab);
                    }
                    else
                    {
                        MessageBox.Show(result);
                    }
                }
            }
        }

        /// <summary>
        /// Makes the new tab.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        private XtraTabPage MakeNewTab(string name)
        {
            XtraTabPage t = new XtraTabPage();
            t.Text = name;
            t.AutoScroll = true;
            if (name == "Welcome")
                t.ShowCloseButton = DevExpress.Utils.DefaultBoolean.False;
            this.tabMain.TabPages.Add(t);
            return t;
        }
        /// <summary>
        /// Makes the new group control.
        /// </summary>
        /// <param name="title">The title</param>
        /// <returns></returns>
        public BaseCaptionControl MakeNewGroupControl(string title)
        {
            var gc = new BaseCaptionControl();
            gc.LookAndFeel.SetSkinStyle("Money Twins");
            gc.Dock = DockStyle.Fill;
            gc.Title = title;
            return gc;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.LoadWelcomeTab();
        }

        private void menuHotel_ItemClick(object sender, ItemClickEventArgs e)
        {
            var x = Common.Common.NewProcessingDialog(this, "Opening... Please wait!");
            this.OpenTab(new ucHotelDetail { Title = "Chi tiết KS" });
            x.EndProcessing();
        }

        private void menuUpEmpRoom_ItemClick(object sender, ItemClickEventArgs e)
        {
            var x = Common.Common.NewProcessingDialog(this, "Đang mở...");
            OpenTab(new ucBookingList2 { Title = "DS đặt phòng" });
            x.EndProcessing();
        }

        private void biUpdateRoom_ItemClick(object sender, ItemClickEventArgs e)
        {
            var x = Common.Common.NewProcessingDialog(this, "Đang mở...");
            OpenTab(new ucUpdateEmptyRoom { 
                Title = "Cập nhật DS phòng trống" ,
                HotelId = 1
            });
            x.EndProcessing();
        }

        

        private void biHotelList_ItemClick(object sender, ItemClickEventArgs e)
        {
            OpenHotelList();
        }

        public void OpenHotelList()
        {
            var x = Common.Common.NewProcessingDialog(this, "Đang mở...");
            OpenTab(new ucHotelList { Title = "DS khách sạn" });
            x.EndProcessing();
        }

        public void OpenHotelInfo()
        {
            var x = Common.Common.NewProcessingDialog(this, "Đang mở...");
            OpenTab(new ucHotelInfor { Title = "Thông tin khách sạn" });
            x.EndProcessing();
        }

        private void miLoaiPhong_ItemClick(object sender, ItemClickEventArgs e)
        {
            var x = Common.Common.NewProcessingDialog(this, "Đang mở...");
            OpenTab(new ucTypeRoom { Title = "DS loại phòng" });
            x.EndProcessing();
        }

        private void biPermission_ItemClick(object sender, ItemClickEventArgs e)
        {
            var x = Common.Common.NewProcessingDialog(this, "Đang mở...");
            OpenTab(new ucUserList { Title = "Phân quyền" });
            x.EndProcessing();
        }

        private void biLogout_ItemClick(object sender, ItemClickEventArgs e)
        {
            var dresult = MessageBox.Show("Bạn có muốn thoát đăng xuất ?", "Thông báo", MessageBoxButtons.YesNo);
            if (dresult == System.Windows.Forms.DialogResult.Yes)
            {
                for (int i = 0; i < this.tabMain.TabPages.Count; i++)
                {
                    var tabPage = this.tabMain.TabPages[i];
                    var ctrl = tabPage.Controls.Count > 0 ? tabPage.Controls[0] : null;
                    if (ctrl != null)
                    {
                        if (ctrl is BaseCaptionControl)
                        {
                            string result = (ctrl as BaseCaptionControl).GetBaseUserControl().Validate();

                            if (result != string.Empty)
                            {
                                var dresult2 = MessageBox.Show("Form '" + tabPage.Text + "' chưa được lưu. Dừng lại để lưu ?", "Thông báo", MessageBoxButtons.YesNo);
                                if (dresult2 == System.Windows.Forms.DialogResult.No)
                                {
                                    this.CloseTab(tabPage.Text);
                                    continue;
                                }
                            }
                            else
                                this.CloseTab(tabPage.Text);
                        }

                    }
                }
                this.LoadWelcomeTab();
            }

        }

        private void biExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show("Bạn có muốn thoát chương trình ?", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.Close();
            }
        }

        private void miNewsList_ItemClick(object sender, ItemClickEventArgs e)
        {
            var x = Common.Common.NewProcessingDialog(this, "Đang mở...");
            OpenTab(new ucNewsList { Title = "DS Tin tức" });
            x.EndProcessing();
        }

        private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            var x = Common.Common.NewProcessingDialog(this, "Đang mở...");
            OpenTab(new ucAbout { Title = "Về Simplesoft" });
            x.EndProcessing();
        }

        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show("Bạn có muốn thoát khỏi chương trình ?", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes) {
                Application.Exit();
            }
        }

        private void biLogin_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.LoadWelcomeTab();           
        }

        private void biHotelInfor_ItemClick(object sender, ItemClickEventArgs e)
        {
            OpenHotelInfo();
        }

        private void tabMain_CloseButtonClick(object sender, EventArgs e)
        {
            TabCloseButtonClick();
        }

    }
}